package com.hejia.alauda.utils;

import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.codec.binary.StringUtils.getBytesUtf8;
import static org.apache.commons.codec.binary.StringUtils.newStringUtf8;
import static org.apache.commons.codec.CharEncoding.UTF_8;
import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString;
import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64String;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryption {
	
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
		            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	public static String sha1(String str){
		String s = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
			messageDigest.update(str.getBytes());
			byte[] bytes = messageDigest.digest();
			int len = bytes.length;
			StringBuilder buf = new StringBuilder(len * 2);
			// 把密文转换成十六进制的字符串形式
			for (int j = 0; j < len; j++) {
				buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
				buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
			}
			s = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return s;
	}
	
	public static String encrypt(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes(UTF_8));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}
	
	public static String urlEncode(String url) {
		return isNotBlank(url) ? encodeBase64URLSafeString(getBytesUtf8(url))
				: url;
	}
	
	public static String urlDecode(String url) {
		return isNotBlank(url) ? newStringUtf8(decodeBase64(getBytesUtf8(url)))
				: url;
	}
	
	public static String urlEncodeUnsafe(String url){
		return isNotBlank(url) ? encodeBase64String(getBytesUtf8(url))
				: url;
	}
	
	/**
	 * 混淆
	 * @param mobile
	 * @return
	 */
	public static String obfuscated(String str,int prefix,int suffix){
		if (isNotBlank(str) && prefix >= 0 && suffix >= 0 && str.length()>(prefix+suffix)) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < str.length(); i++) {
				if (i < prefix || (str.length() - i) <= suffix) {
					sb.append(str.charAt(i));
				} else {
					sb.append('*');
				}
			}
			str = sb.toString();
		}
		return str;
	}
	
	/**
	 * 混淆姓名
	 * @param str
	 * @return
	 */
	public static String obfuscatedName(String str) {
		if(isNotBlank(str)){
			if(str.length()==2){
				str = "*" + str.substring(1);
			} else if(str.length()>2){
				str = Encryption.obfuscated(str,1,1);
			}
		}
		return str;
	}
	
	public static String obfuscatedMobile(String str) {
		if(isNotBlank(str)){
			StringBuilder sb = new StringBuilder(str);
			if(sb.length()>7) {
				sb = sb.replace(3, 7, "****");
			}
			str = sb.toString();
		}
		return str;
	}
	
	public static String AESEncrypt(String encData ,String secretKey,String vector) throws Exception {
		
		if(secretKey == null) {
			return null;
		}
		if(secretKey.length() != 16) {
			return null;
		}
		byte[] raw = secretKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
		IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(encData.getBytes());
		return encodeBytes(encrypted);
	}
	
	public static String encodeBytes(byte[] bytes) {
		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
			strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
		}
		return strBuf.toString();
	}
	
	public static String getMD5(String comeString) {

		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };// 用来将字节转换成16进制表示的字符
		byte sources[] = comeString.getBytes();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sources);
			byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2];// 每个字节用 16 进制表示的话，使用两个字符，所以表示成 16
			// 进制需要 32 个字符
			int k = 0;// 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) {// 从第一个字节开始，对 MD5 的每一个字节// 转换成 16
				// 进制字符的转换
				byte byte0 = tmp[i];// 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
				// 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换
			}

			s = new String(str);// 换后的结果转换为字符串

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return s;
	}
	
	public static void main(String[] args) throws Exception {
		
		String content ="TEST1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		System.out.println(AESEncrypt(content, "H5gOs1ZshKZ6WikN", "8888159601152533"));
	}
}
